package com.financing.wap.web.controller.api;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.financing.wap.dto.*;
import com.financing.wap.service.*;
import com.financing.wap.util.PropertiesUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;
import cn.jpush.api.utils.Base64;

@Controller("fpClientOrderController")
@RequestMapping("/api/fpClientOrder")
public class FpClientOrderController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IFpClientOrderService fpClientOrderService;
	
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	
	@Autowired
	private IProductService productService;
	
	@Autowired
	private ISmsNewService smsNewService;

	@Autowired
	private IMessageJpushUserPhoneAliasService messageJpushUserPhoneAliasService;

	@Autowired
	private IUserService userService;
	@Autowired
	private ICheckCodeService checkCodeServiceImpl;

	/***
	 * 
	
	* @Title: list
	
	* @Description: 当前用户店铺订单
	
	* @param @param request
	* @param @param fpClientOrder
	* @param @param pager
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/listFpClientOrder")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, FpClientOrderDTO fpClientOrder,Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query fpClientOrder list begin .......");
			
			fpClientOrder.setBegin(pager.getStartIndex());
			fpClientOrder.setPageSize(pager.getPageSize());
			
			// 登录用户查看自己店铺预约订单信息
			UserDTO u = SessionUtil.getSession().getUser();
			if(null == u){
				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			fpClientOrder.setShopperId(u.getLoginName());
			
			int count = fpClientOrderService.queryListCount(fpClientOrder);
			
			pager.setTotalCount(count);
			
			List<FpClientOrderDTO> fpClientOrderList = null;
			
			if(count > 0){
				fpClientOrderList = fpClientOrderService.queryList(fpClientOrder);
			}else{
				fpClientOrderList = Collections.emptyList();
			}
			result.setAttribute("pager", pager);
			result.setAttribute("list", fpClientOrderList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query fpClientOrder list end .......");
		}catch(Exception e){
			log.error("query fpClientOrder error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	@RequestMapping("/addFpClientOrder")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, FpClientOrderDTO fpClientOrder){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add fpClientOrder  begin .......");
			
			String pId=fpClientOrder.getProductId();
			String pType=fpClientOrder.getProductType();
			String shopperId = fpClientOrder.getShopperId();
			String userName = fpClientOrder.getUserName();
			String userPhone = fpClientOrder.getUserPhone();
			BigDecimal reservationAmount = fpClientOrder.getReservationAmount();
			if(null == reservationAmount){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			if(StringUtil.isNullOrEmptyNStr(pId,pType,shopperId, userName, userPhone)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			// 获取登录用户ID
			UserDTO loginUser = this.getSession().getUser();
			if(null != loginUser){
				fpClientOrder.setUserId(loginUser.getLoginName());
			}
			
			
			// 查询出产品信息
			if(pType.equals("01")){//私募基金
				// 查私募基金fp_fund_info表
				FpFundInfoDTO fundInfoDTO = fpFundInfoService.getFpFundInfo(new Integer(pId));
				if(null == fundInfoDTO){
					result.setStatusCode(ResultMap.STATUS_CODE_PROTYPE_NOT_EXIST);
					result.setStatus(ResultMap.STATUS.FAILE);
					return result;
				}
				fpClientOrder.setProductName(fundInfoDTO.getJjmc());
			}else if(pType.equals("02") || pType.equals("03") || pType.equals("06")|| pType.equals("07")){
				// 查产品fp_project表 p_code
				ProductBasicInfoDTO basicInfoDTO = productService.queryBasicInfo(pId);
				if(null == basicInfoDTO){
					result.setStatusCode(ResultMap.STATUS_CODE_PROTYPE_NOT_EXIST);
					result.setStatus(ResultMap.STATUS.FAILE);
					return result;
				}
				fpClientOrder.setProductName(basicInfoDTO.getName());
			}
			
			
			String validatecode = request.getParameter("validatecode");
			String mobile = request.getParameter("userPhone");
//			String loginName= loginUser.getLoginName();
			
			//检查数据是否为空
			if(StringUtils.isBlank(validatecode) && StringUtils.isBlank(loginUser.getLoginName())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			
			//验证码判断
			if(!StringUtils.isBlank(validatecode)){
				//手机验证码
				if(checkCodeServiceImpl.CheckCodeSwitch()){
					Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
					//验证码超时
					if(checkOtpCodeTimeOut(mobile,activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
						result.setStatus(ResultMap.STATUS.FAILE);
						result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
						result.setMessage("手机验证码超时！");
						return result;
						
					};
					ResultMap resultOtp = checkOtpCode(mobile,validatecode);
					if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
						result.setStatus(resultOtp.getStatus());
						result.setStatusCode(resultOtp.getStatusCode());
						result.setMessage(resultOtp.getMessage());
						return result;
					}
				}
			}
			
			
			
			int id = fpClientOrderService.insert(fpClientOrder);
			result.setAttribute("id", id);
			
			try {
				//发送短信 
				String content="您的客户【%s】，预约了【%s】，金额【%s】万元，请及时跟进。";
				String productName = fpClientOrder.getProductName();
				content=String.format(content, mobile,productName,reservationAmount);
				List mobileList=new ArrayList<String>();
				mobileList.add(shopperId);
				smsNewService.sendSms(mobileList,content,"ClientOrderSendSms");

				//// 访问推送
				// 极光推送消息

				logger.info("goto jpush shopId: "+shopperId);

				UserDTO userDTO = new UserDTO();
				userDTO.setLoginName(shopperId);
				userDTO = userService.queryUserLoginName(userDTO);

				logger.info("goto url shopId: "+shopperId);

				// 根据用户查询出绑定的设备标示
				MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
				dto.setFpUserId(userDTO.getId());
				MessageJpushUserPhoneAliasDTO phoneAlias = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
				if(null != phoneAlias ){
					String contentJpush = "【%s】，客户姓名【%s】，金额【%s】万，手机号码【%s】请及时处理";
					contentJpush=String.format(contentJpush, productName,userName,reservationAmount,userPhone);
					logger.info("goto jpush: "+shopperId);
					MessageJpushDTO messageJpushDTO = new MessageJpushDTO();

					messageJpushDTO.setFpJpushMsgRec(phoneAlias.getFpJpushAliasShop());
					messageJpushDTO.setFpJpushTitle("金策师");
					messageJpushDTO.setFpJpushContent(contentJpush);
					messageJpushDTO.setFpJpushRedrict(new String(Base64.encode(PropertiesUtils.getValue("jiGuangPushRedrictShopOrder").getBytes())));
					messageJpushDTO.setFpJpushMsgType("03");// 消息类型 01:系统消息 02:运营推送
					messageJpushDTO.setFpJpushSendType("01");// 推送消息类型  01:实时推送  02:定时推送
					messageJpushDTO.setCreateBy("");
					messageJpushDTO.setCreateDate(new Date());
					messageJpushDTO.setUpdateBy("");
					messageJpushDTO.setUpdateDate(new Date());
					messageJpushDTO.setFpJpushShopType("1");
					messageJpushDTO.setFpJpushSource("shop");
					messageJpushUserPhoneAliasService.addJpushMessage(messageJpushDTO);
				}
			} catch (Exception e) {
				log.error(" ClientOrderSendSms send error!",e);
			}
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add fpClientOrder list end .......");
		}catch(Exception e){
			log.error("add fpClientOrder error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
}
